__author__ = 'graced'

import urllib2
import riak
from xml.etree import ElementTree as ET

class Case:
    def __init__(self):
        self.key = []
        self.value = []
        self.data = {}

    def addData(self, key, value):
        self.data[key] = value

    def getAllData(self):
        return self.data

    def getData(self, key):
        return self.data[key]

class RiakQuery:
    def __init__(self):
        pass

    def executeQuery(self, field, value):
        cases = []
        URL = "http://localhost:8098/search/query/xml1?q=dicom.image."+field+":"+value+"&wt=python"
        connection = urllib2.urlopen(URL)
        response = eval(connection.read())

        for document in response['response']['docs']:
            currentCase = Case()
            XML = "http://localhost:8098/types/xml1/buckets/xml1/keys/"+document['_yz_rk']
            tree = ET.ElementTree(file=urllib2.urlopen(XML))
            root = tree.getroot()
            metaData = {}
            imageData = {}

            for node in root.getchildren()[0]:
                metaData[node.tag] = node.text
            for node in root.getchildren()[1]:
                imageData[node.tag] = node.text
                for item in node.findall("item"):
                    itemCounter = 1
                    for subItem in item:
                        imageData[subItem.tag+"_"+str(itemCounter)] = subItem.text
                        itemCounter += 1

            for item in metaData:
                currentCase.addData(item, metaData[item])

            for item in imageData:
                currentCase.addData(item, imageData[item])

            cases.append(currentCase)

        print "Cases found:", cases.__len__(), "\n"
        for case in cases:
            #print case.getAllData()
            print case.getData('PatientName')
            print case.getData('PatientID')
            print case.getData('DerivationDescription')
            print "\n"

tempQuery = RiakQuery()
tempQuery.executeQuery("SliceLocation", "13.88194752")
